import { createApp, watchEffect } from 'vue';

import { registerAuthDirective } from '@croco/framework/access';
import { registerSpinningDirective } from '@croco/framework/libraries';
import { preferences } from '@croco/framework/preferences';
import { initStores } from '@croco/framework/stores';
import '@croco/styles';
import '@croco/styles/ele';

import { useTitle } from '@vueuse/core';

import { $t, setupI18n } from '#/locales';

import App from './app.vue';
import { router } from './router';

async function bootstrap(namespace: string) {
    const app = createApp(App);

    // 注册Element Plus提供的v-loading指令
    // app.directive('loading', ElLoading.directive);

    // 注册Vben提供的v-loading和v-spinning指令
    // registerLoadingDirective(app, {
    //     loading: false, // Vben提供的v-loading指令和Element Plus提供的v-loading指令二选一即可，此处false表示不注册Vben提供的v-loading指令
    //     spinning: 'spinning',
    // });
    // 扩展loading样例
    registerSpinningDirective((directive) => app.directive('spinning', directive));

    // 国际化 i18n 配置
    await setupI18n(app);

    // 配置 pinia-tore
    await initStores(app, { namespace });

    // 安装权限指令
    registerAuthDirective((directive) => app.directive('auth', directive));

    // 初始化 tippy
    const { initTippy } = await import('@croco/framework/libraries');
    await initTippy(app);

    // 配置路由及路由守卫
    app.use(router);

    // 配置Motion插件
    const { MotionPlugin } = await import('@croco/plugins/motion');
    app.use(MotionPlugin);

    // 动态更新标题
    watchEffect(() => {
        if (preferences.app.dynamicTitle) {
            const routeTitle = router.currentRoute.value.meta?.title;
            const pageTitle = (routeTitle ? `${$t(routeTitle)} - ` : '') + preferences.app.name;
            useTitle(pageTitle);
        }
    });

    app.mount('#app');
}

export { bootstrap };
